package com.atguigu.eduteacher.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.eduteacher.javabean.EduSubject;
import com.atguigu.eduteacher.javabean.ExcelSubjectData;
import com.atguigu.eduteacher.javabean.SubjectNestedDto;
import com.atguigu.eduteacher.javabean.SubjectDto;
import com.atguigu.eduteacher.listener.SubjectExcelListener;
import com.atguigu.eduteacher.mapper.EduSubjectMapper;
import com.atguigu.eduteacher.service.EduSubjectService;
import com.atguigu.servicebase.exception.GuliException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-11-15
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper,
        EduSubject> implements EduSubjectService {

    @Override
    public void importSubjectData(MultipartFile file) {
        try {
            //1 获取文件输入流
            InputStream inputStream = file.getInputStream();
            // 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
            EasyExcel.read(inputStream, ExcelSubjectData.class,
                    new SubjectExcelListener(this)).sheet().doRead();
        } catch (Exception e) {
            e.printStackTrace();
            throw new GuliException(20002, "添加课程分类失败");
        }
    }

    @Override
    public List<SubjectNestedDto> nestedList() {
        //最终要的到的数据列表
        List<SubjectNestedDto> subjectNestedDtoArrayList;
        //获取一级分类数据记录
        QueryWrapper<EduSubject> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", 0);
        List<EduSubject> subjects = baseMapper.selectList(queryWrapper);
        //获取二级分类数据记录
        QueryWrapper<EduSubject> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.ne("parent_id", 0);
        List<EduSubject> subSubjects = baseMapper.selectList(queryWrapper2);

        //一级课程
        subjectNestedDtoArrayList =
                subjects.stream().map(item -> new SubjectNestedDto(item.getId(), item.getTitle())
                ).collect(Collectors.toList());


        //过滤出二级课程，并转换为目标对象
        subjectNestedDtoArrayList.stream().forEach(item -> {
            List<SubjectDto> collect =
                    subSubjects.stream().filter(subItem -> item.getId().equals(subItem.getParentId())).map(subItem -> new SubjectDto(subItem.getId(),
                            subItem.getTitle())).collect(Collectors.toList());
            item.setChildren(collect);
        });
        return subjectNestedDtoArrayList;
    }
}
